package com.gome.axwl.aoc.web.util;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Map.Entry;

public class BeanUtil {

    public static <T> String getFieldStringValue(T bean, String fieldName) {
        if (bean == null || fieldName == null) {
            return "";
        }
        Object object = getFieldValue(bean, fieldName);
        return object + "";
    }

    public static <T> Object getFieldValue(T bean, String fieldName) {
        Object object = null;
        if (bean == null || fieldName == null) {
            return object;
        }
        try {
            Class<? extends Object> cls = bean.getClass();
            Field field = cls.getDeclaredField(fieldName);
            field.setAccessible(true);
            object = field.get(bean);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return object;
    }
    
    public static <T> void setFieldValue(T bean, String fieldName, Object value) {
        if (bean == null || fieldName == null || value == null) {
            return;
        }
        try {
            Class<? extends Object> cls = bean.getClass();
            Field field = cls.getDeclaredField(fieldName);
            field.setAccessible(true);
            if (String.class == field.getType()) {
                value = value + "";
            }
            if (Integer.class == field.getType()) {
                value = Integer.parseInt(value + "");
            }
            field.set(bean, value);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    
    public static <F, T> T trasferBean(F bean, Class<T> cls , Map<String, String> map) {
        if (bean == null || map == null) {
            return null;
        }
        T t = null;
        try {
            t = cls.newInstance();
            for (Entry<String, String> entry : map.entrySet()) {
                String fromFieldName = entry.getKey();
                String toFieldName = entry.getValue();
                Object fieldValue = getFieldValue(bean, fromFieldName);
                setFieldValue(t, toFieldName, fieldValue);
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return t;
    }
}
